package com.wy.pdf_test;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.concurrent.Worker;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@Service
public class HtmlToPdfRenderer extends Application {

    private static String htmlUrl;
    private static String outputPdf;

    public static void render(String htmlPathOrUrl, String pdfOutputPath) {
        htmlUrl = htmlPathOrUrl;
        outputPdf = pdfOutputPath;
        launch(); // 启动 JavaFX 应用
    }

    @Override
    public void start(Stage stage) {
        WebView webView = new WebView();
        WebEngine engine = webView.getEngine();

        // 设置页面大小（根据需要调整）
        webView.setPrefWidth(1100);
        webView.setPrefHeight(1300);

        // 监听网页加载状态
        engine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
            System.out.println("页面加载状态：" + newState);
            if (newState == Worker.State.SUCCEEDED) {
                System.out.println("✅ 页面初步加载完成");

                // 等待 JS 执行完毕（可调整时间）
                new Thread(() -> {
                    try {
                        Thread.sleep(5000); // 等待 JS 动态渲染（根据实际情况调整）
                        Platform.runLater(() -> takeSnapshotAndSave(webView));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        });

        // 加载 HTML 页面（支持 file:// 或 http(s)://）
        engine.load(htmlUrl);

        // 可选：显示窗口，开发调试用
        stage.setScene(new Scene(webView));
        stage.setTitle("HTML Renderer");
        stage.show();
    }

    private void takeSnapshotAndSave(WebView webView) {
        webView.snapshot(result -> {
            BufferedImage image = SwingFXUtils.fromFXImage(result.getImage(), null);
            try {
                File imgFile = new File("temp_render.png");
                ImageIO.write(image, "png", imgFile);
                saveImageToPDF(imgFile, new File(outputPdf));
                System.out.println("✅ PDF saved to: " + outputPdf);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Platform.exit(); // 关闭 JavaFX 应用
            return null;
        }, null, null);
    }

//    private void saveImageToPDF(File imageFile, File outputPdf) throws IOException {
//        PDDocument doc = new PDDocument();
//        PDPage page = new PDPage();
//        doc.addPage(page);
//
//        PDImageXObject pdImage = PDImageXObject.createFromFile(imageFile.getAbsolutePath(), doc);
//        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
//
//        // 适配 PDF 页面大小（这里是简单缩放）
//        contentStream.drawImage(pdImage, -50, 50, 700, 700);
//        contentStream.close();
//
//        doc.save(outputPdf);
//        doc.close();
//    }

    private void saveImageToPDF(File imageFile, File outputPdf) throws IOException {
        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);

        // 加载图片
        BufferedImage bufferedImage = ImageIO.read(imageFile);
        int imgWidth = bufferedImage.getWidth();
        int imgHeight = bufferedImage.getHeight();

        PDImageXObject pdImage = PDImageXObject.createFromFileByContent(imageFile, doc);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);

        // 获取 PDF 页面宽高（以点为单位，1 pt = 1/72 inch）
        float pageWidth = page.getMediaBox().getWidth();
        float pageHeight = page.getMediaBox().getHeight();

        // 目标宽度为页面宽度（可以减去边距）
        float targetWidth = pageWidth - 40; // 留边距左右各 20
        float scale = targetWidth / imgWidth;
        float targetHeight = imgHeight * scale;

        // 设定绘图位置（x 左右边距 20，y 顶部对齐或居中）
        float x = 20;
        float y = pageHeight - targetHeight - 40; // 距顶部 40pt

        contentStream.drawImage(pdImage, x, y, targetWidth, targetHeight);
        contentStream.close();

        doc.save(outputPdf);
        doc.close();
    }



    public static void main(String[] args) {
        // 支持本地文件或远程 URL（记得用 file:/// ）
        render("file:///D:/projects/code/study/sketch-study/examReport.html", "1output.pdf");
    }
}
